<template>
  <view class="order-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">我的订单</text>
    </view>

    <!-- 订单状态筛选 -->
    <view class="status-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === item.key }"
        v-for="item in statusTabs" 
        :key="item.key"
        @tap="switchTab(item.key)"
      >
        <text class="tab-text">{{ item.label }}</text>
        <view class="tab-badge" v-if="item.count > 0">
          <text class="badge-text">{{ item.count }}</text>
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view class="order-item" v-for="order in filteredOrders" :key="order.id" @tap="viewOrderDetail(order.id)">
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-number">订单号：{{ order.id }}</text>
          <text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
        </view>
        
        <!-- 商品信息 -->
        <view class="product-info">
          <image class="product-image" :src="order.productImage" mode="aspectFill"></image>
          <view class="product-details">
            <text class="product-name">{{ order.productName }}</text>
            <text class="product-spec" v-if="order.productSpec">规格：{{ order.productSpec }}</text>
            <view class="product-price-qty">
              <text class="product-price">¥{{ order.productPrice }}</text>
              <text class="product-qty">x{{ order.quantity }}</text>
            </view>
          </view>
        </view>
        
        <!-- 订单信息 -->
        <view class="order-info">
          <view class="info-row">
            <text class="info-label">收货人：</text>
            <text class="info-value">{{ order.address.name }} {{ order.address.phone }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">收货地址：</text>
            <text class="info-value">{{ order.address.fullAddress }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">订单金额：</text>
            <text class="info-value amount">¥{{ order.totalAmount }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">下单时间：</text>
            <text class="info-value">{{ formatTime(order.createTime) }}</text>
          </view>
          <view class="info-row" v-if="order.payTime">
            <text class="info-label">支付时间：</text>
            <text class="info-value">{{ formatTime(order.payTime) }}</text>
          </view>
          <view class="info-row" v-if="order.deliveryTime">
            <text class="info-label">发货时间：</text>
            <text class="info-value">{{ formatTime(order.deliveryTime) }}</text>
          </view>
          <view class="info-row" v-if="order.trackingNumber">
            <text class="info-label">快递单号：</text>
            <text class="info-value tracking">{{ order.trackingNumber }}</text>
          </view>
        </view>
        
        <!-- 订单操作 -->
        <view class="order-actions">
          <view class="action-btn secondary" v-if="order.status === 'pending'" @tap.stop="cancelOrder(order.id)">
            <text class="btn-text">取消订单</text>
          </view>
          <view class="action-btn primary" v-if="order.status === 'pending'" @tap.stop="payOrder(order.id)">
            <text class="btn-text">立即支付</text>
          </view>
          <view class="action-btn secondary" v-if="order.status === 'shipped'" @tap.stop="confirmReceived(order.id)">
            <text class="btn-text">确认收货</text>
          </view>
          <view class="action-btn secondary" v-if="order.status === 'delivered'" @tap.stop="contactService(order.id)">
            <text class="btn-text">联系客服</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0">
        <image class="empty-icon" src="/static/images/empty-order.png" mode="aspectFit"></image>
        <text class="empty-text">暂无相关订单</text>
        <view class="empty-btn" @tap="goShopping">
          <text class="empty-btn-text">去购物</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'

// 响应式数据
const activeTab = ref('all')
const orderList = ref([])
const loading = ref(false)

// 状态标签配置
const statusTabs = computed(() => {
  const counts = {
    all: orderList.value.length,
    pending: orderList.value.filter(order => order.status === 'pending').length,
    paid: orderList.value.filter(order => order.status === 'paid').length,
    shipped: orderList.value.filter(order => order.status === 'shipped').length,
    delivered: orderList.value.filter(order => order.status === 'delivered').length
  }
  
  return [
    { key: 'all', label: '全部', count: counts.all },
    { key: 'pending', label: '待支付', count: counts.pending },
    { key: 'paid', label: '待发货', count: counts.paid },
    { key: 'shipped', label: '待收货', count: counts.shipped },
    { key: 'delivered', label: '已完成', count: counts.delivered }
  ]
})

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orderList.value
  }
  return orderList.value.filter(order => order.status === activeTab.value)
})

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  
  try {
    // 这里应该调用后端API获取订单列表
    // const res = await api.getOrderList()
    // orderList.value = res.data
    
    // 临时从本地存储获取
    const orders = uni.getStorageSync('orderList') || []
    orderList.value = orders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
  } catch (error) {
    console.error('加载订单列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 切换标签
const switchTab = (tabKey) => {
  activeTab.value = tabKey
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待支付',
    paid: '待发货',
    shipped: '待收货',
    delivered: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  return `status-${status}`
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderId}`
  })
}

// 取消订单
const cancelOrder = async (orderId) => {
  const result = await uni.showModal({
    title: '确认取消',
    content: '确定要取消这个订单吗？',
    confirmText: '确定',
    cancelText: '取消'
  })
  
  if (!result.confirm) return
  
  try {
    // 这里应该调用后端API取消订单
    // await api.cancelOrder(orderId)
    
    // 临时更新本地存储
    let orders = uni.getStorageSync('orderList') || []
    const orderIndex = orders.findIndex(order => order.id === orderId)
    
    if (orderIndex > -1) {
      orders[orderIndex].status = 'cancelled'
      uni.setStorageSync('orderList', orders)
      loadOrderList()
    }
    
    uni.showToast({
      title: '订单已取消',
      icon: 'success'
    })
    
  } catch (error) {
    console.error('取消订单失败:', error)
    uni.showToast({
      title: '取消失败',
      icon: 'none'
    })
  }
}

// 支付订单
const payOrder = (orderId) => {
  const order = orderList.value.find(o => o.id === orderId)
  if (order) {
    uni.navigateTo({
      url: `/pages/payment/payment?orderId=${orderId}&amount=${order.totalAmount}`
    })
  }
}

// 确认收货
const confirmReceived = async (orderId) => {
  const result = await uni.showModal({
    title: '确认收货',
    content: '确认已收到商品吗？',
    confirmText: '确认',
    cancelText: '取消'
  })
  
  if (!result.confirm) return
  
  try {
    // 这里应该调用后端API确认收货
    // await api.confirmReceived(orderId)
    
    // 临时更新本地存储
    let orders = uni.getStorageSync('orderList') || []
    const orderIndex = orders.findIndex(order => order.id === orderId)
    
    if (orderIndex > -1) {
      orders[orderIndex].status = 'delivered'
      orders[orderIndex].receivedTime = new Date().toISOString()
      uni.setStorageSync('orderList', orders)
      loadOrderList()
    }
    
    uni.showToast({
      title: '确认收货成功',
      icon: 'success'
    })
    
  } catch (error) {
    console.error('确认收货失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 联系客服
const contactService = (orderId) => {
  uni.showModal({
    title: '联系客服',
    content: '如需帮助，请联系客服微信：petbone2024',
    showCancel: false,
    confirmText: '知道了'
  })
}

// 去购物
const goShopping = () => {
  uni.switchTab({
    url: '/pages/shop/shop'
  })
}

// 生命周期
onShow(() => {
  loadOrderList()
})

onMounted(() => {
  loadOrderList()
})
</script>

<style scoped>
.order-page {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 页面标题 */
.page-header {
  background: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 状态标签 */
.status-tabs {
  background: white;
  display: flex;
  padding: 0 16px;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  padding: 16px 8px;
  text-align: center;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #FFB800;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 2px;
  background: #FFB800;
}

.tab-text {
  font-size: 14px;
  color: inherit;
}

.tab-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #FF4444;
  border-radius: 10px;
  min-width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.badge-text {
  font-size: 10px;
  color: white;
  line-height: 1;
}

/* 订单列表 */
.order-list {
  padding: 16px;
}

.order-item {
  background: white;
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-number {
  font-size: 14px;
  color: #666;
}

.order-status {
  font-size: 14px;
  font-weight: bold;
}

.status-pending {
  color: #FF9800;
}

.status-paid {
  color: #2196F3;
}

.status-shipped {
  color: #9C27B0;
}

.status-delivered {
  color: #4CAF50;
}

.status-cancelled {
  color: #999;
}

/* 商品信息 */
.product-info {
  padding: 16px 20px;
  display: flex;
  gap: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  line-height: 1.3;
}

.product-spec {
  font-size: 12px;
  color: #999;
}

.product-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.product-price {
  font-size: 16px;
  color: #FF4444;
  font-weight: bold;
}

.product-qty {
  font-size: 14px;
  color: #666;
}

/* 订单信息 */
.order-info {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  flex: 0 0 80px;
  font-size: 12px;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 12px;
  color: #333;
  line-height: 1.3;
}

.info-value.amount {
  color: #FF4444;
  font-weight: bold;
}

.info-value.tracking {
  color: #FFB800;
}

/* 订单操作 */
.order-actions {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 16px;
  border: 1px solid #ddd;
  transition: all 0.3s ease;
}

.action-btn.primary {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-color: #FFB800;
}

.action-btn.secondary {
  background: white;
  border-color: #ddd;
}

.action-btn:active {
  transform: translateY(1px);
}

.btn-text {
  font-size: 12px;
  color: #333;
}

.action-btn.primary .btn-text {
  color: white;
}

/* 空状态 */
.empty-state {
  padding: 80px 40px;
  text-align: center;
}

.empty-icon {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 14px;
  color: #999;
  display: block;
  margin-bottom: 24px;
}

.empty-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 20px;
  padding: 10px 24px;
  display: inline-block;
}

.empty-btn-text {
  font-size: 14px;
  color: white;
  font-weight: bold;
}
</style>